//
//  ApiSeriver.m
//  QFBAPP
//
//  Created by 无常先生 on 2018/5/2.
//  Copyright © 2018年 YIXun. All rights reserved.
//

#import "ApiSeriver.h"
#import <ReactiveObjC/ReactiveObjC.h>
#import "AFNetworkReachabilityManager.h"

@interface ApiSeriver()

@property (nonatomic, strong) AFNetworkReachabilityManager *reachability;

@property (nonatomic, strong) NSMutableDictionary *dictionaryOfServerUrls;

@property (nonatomic, assign) AFNetworkReachabilityStatus netWorkStatus;

@property (nonatomic, strong, readwrite) NSNumber *networkType;
@end

static RACSubject *networkStatusSubject;


@implementation ApiSeriver

@synthesize serverType = _serverType;

- (instancetype)init {
    self = [super init];
    if (self) {
        _dictionaryOfServerUrls = [NSMutableDictionary dictionaryWithCapacity:3];
        
        self.reachability = [AFNetworkReachabilityManager sharedManager];
         @weakify(self);
        [self.reachability setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
            @strongify(self);
            self.networkType = @(status);
            if (networkStatusSubject) {
                [networkStatusSubject sendNext:@(status)];
            }
        }];
    }
    return self;
}

- (void)setServerUrl:(NSString *)serverUrl forServerType:(ApiServerType)serverType {
    if ([[_dictionaryOfServerUrls objectForKey:@(serverType)] isEqualToString:serverUrl]) {
        return;
    }
    [_dictionaryOfServerUrls setObject:serverUrl forKey:@(serverType)];
    if (_serverType != serverType) {
        return;
    }
}

- (void)startMonitoring {
    [_reachability startMonitoring];
}

- (void)stopMonitoring {
    [_reachability stopMonitoring];
}

#pragma mark - properties

- (void)setServerType:(ApiServerType)serverType {
    if (serverType == ApiServerTypeNone || _serverType == serverType) {
        return;
    }
    _serverType = serverType;
}

- (NSString *)serverUrl {
    return _serverType == ApiServerTypeNone ? nil : [_dictionaryOfServerUrls objectForKey:@(_serverType)];
}

- (NetworkStatus)networkStatus {
    return (NetworkStatus)_reachability.networkReachabilityStatus;
}

- (BOOL)isReachable {
    return _reachability.reachable;
}

- (BOOL)isReachableViaWWAN {
    return _reachability.reachableViaWWAN;
}

- (BOOL)isReachableViaWiFi {
    return _reachability.reachableViaWiFi;
}


- (RACSignal *)networkStatusSignal {
    return networkStatusSubject
    ?: (networkStatusSubject = [[RACSubject subject] setNameWithFormat:@"networkStatusSignal"]);
}
@end
